package com.qk.management.task;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ListObjectsV2Request;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import com.qk.common.config.AliYunOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class OssFileLister {
    @Autowired
    private AliYunOSSProperties aliYunOSSProperties ;
    public List<String > listFiles(){

        // 创建OSSClient实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        // 初始化列表，解决空指针问题
        List<String> objectSummaries = new ArrayList<>();
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();
            // 分页列举所有文件
            String nextMarker = null;

            do {
                // 创建ListObjectsV2请求
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(aliYunOSSProperties.getBucketName());

                listObjectsV2Request.setContinuationToken(nextMarker);
                listObjectsV2Request.setMaxKeys(1000);
                // 执行列举请求
                ListObjectsV2Result result = ossClient.listObjectsV2(listObjectsV2Request);

                // 处理当前页的文件
                for (OSSObjectSummary objectSummary : result.getObjectSummaries()){
                    objectSummaries.add(objectSummary.getKey());
                    System.out.println("文件名：" + objectSummary.getKey());
                }

                // 获取下一页标记
                nextMarker = result.getNextContinuationToken();
            } while (nextMarker != null); // 如果有下一页，继续列举

            System.out.println("所有文件列举完成");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return objectSummaries;
    }
}
